﻿
$(function(){
	
	window.BasketItem = Backbone.Model.extend({
		defaults: {
			name: "Ololo Item...",
			img: 'img/no_photo.png',
			price: 1000,
			qty: 1,
		},
		initialize: function() {
			//
		},
		toggle: function() {
		  this.save();
		},
		clear: function() {
		  this.destroy();
		}
	});
  
    window.BasketItemList = Backbone.Collection.extend({
		model: BasketItem,
		localStorage: new Store("basket-items"),
	});
	window.BasketItems = new BasketItemList;
	
	window.BasketOpt = Backbone.Model.extend({
		localStorage: new Store("basket-opts"),
		defaults: {
			status: 0,
		},
		statuses: {
			'0': 1000,
			'1': 2500,
		},
	})
	window.basketOpts = new BasketOpt({id:1})
	
	var BasketOptsView = Backbone.View.extend({
		el: $("#status"),
		template: _.template($('#opts-template').html()),
		initialize: function() {
			this.render()
		},
		render: function() {
			this.$el.html(this.template(this.model.toJSON()))
			.selectpicker({
				btnStyle: 'btn-info'
			});
		},
	})
	
    var BasketItemView = Backbone.View.extend({
		tagName:  "tr",
		template: _.template($('#item-template').html()),
		events: {
			"click div.destroy" : "clear",
			"change input" : "change",
		},
		initialize: function() {
		  this.model.bind('change', this.render, this);
		  this.model.bind('destroy', this.remove, this);
		},
		render: function() {
		  this.$el.html(this.template(this.model.toJSON()));
		  this.input = this.$('input')
		  return this;
		},
		clear: function() {
			this.model.clear();
		},
		change: function(e) {
			var value = this.input.val()*1;
			if(!/^[0-9]+$/.test(value)) {
				//this.render()
				this.input.val(this.model.toJSON().qty)
				return
			}
			if(value>0)
				this.model.save({qty: value});
			else
				this.clear()
		},
	});
  
	var AppView = Backbone.View.extend({
		el: $(".container"),
		template: _.template($('#itog-template').html()),
		events: {
			"change #status": "changeStatus",
			"click #makeOrder": "makeOrder"
		},
		initialize: function() {
			BasketItems.bind('reset', this.addAll, this);
			BasketItems.bind('add', this.addOne, this);
			BasketItems.bind('all', this.render, this);
			basketOpts.bind('change:status', this.render, this);
			this.status = this.$('#status')
			basketOpts.fetch();
			new BasketOptsView({model: basketOpts});
			BasketItems.fetch();
		},
		render: function() {
			var length = BasketItems.length;
			var sum = _.reduce(BasketItems.toJSON(), function(sum, obj){ return sum + obj.price*obj.qty; }, 0);
			sum += length?basketOpts.statuses[this.status.val()]:0;
			this.$('#makeOrder').prop('disabled',!sum)
			this.$('#itog').html(this.template({'sum': sum}));
		},
		addOne: function(item) {
			var view = new BasketItemView({model: item});
			this.$("#basket-items-list").prepend(view.render().el);
		},
		addAll: function() {
			BasketItems.each(this.addOne);			
		},
		changeStatus: function(){
			basketOpts.save({status:this.status.val()})
		},
		makeOrder: function(e){
			this.$('#myModal #placeOrder').unbind('click')
			
			var data = basketOpts.toJSON();
			data.items = BasketItems.toJSON()
			var view = _.template($('#order-template').html())(data)
			this.$('#myModal .modal-body').html(view)
			this.$('#myModal #placeOrder').bind('click',function(){
				_.each(data.items,function(val,key){
					data.items[key] = {id:val.id, qty:val.qty}
				})
				delete data.id;
				console.log('SEND TO SERVER:',data)
				$.ajax({
					url: 'order.jsp',
					type: 'POST',
					data: data,
					success: function(res){
						console.log(res)
					}
				});
				$('#myModal').modal('hide')
				setTimeout(function(){
					$('#ordersMenu').effect('highlight',{color:'#f93'},500).effect('highlight',{color:'#f93'},500)
				},500)
			})
		},
  });

  window.App = new AppView;

});
